package com.cssw.fyzb.job.executor.config;

import com.cssw.fyzb.core.mongo.MongoClient;
import com.cssw.fyzb.core.mongo.MongoOptions;
import com.cssw.fyzb.job.executor.util.StringUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author Feng Chen
 */
@Configuration
public class MongoConfig {

    @Value("${mongo.host}")
    private String host;

    @Value("${mongo.port}")
    private Integer port;

    @Value("${mongo.seeds}")
    private String seeds;

    @Value("${mongo.db}")
    private String db;

    @Value("${mongo.user}")
    private String user;

    @Value("${mongo.pwd}")
    private String pwd;

    @Value("${mongo.options.maxWaitTime}")
    private Integer maxWaitTime;

    @Value("${mongo.options.coTimeout}")
    private Integer coTimeout;

    @Value("${mongo.options.soTimeout}")
    private Integer soTimeout;

    @Value("${mongo.options.coPerHost}")
    private Integer coPerHost;

    @Value("${mongo.options.coMultiplier}")
    private Integer coMultiplier;

    @Bean(destroyMethod = "close")
    public MongoClient mongoClient() {

        MongoOptions options = new MongoOptions();
        options.setMaxWaitTime(maxWaitTime);
        options.setCoTimeout(coTimeout);
        options.setSoTimeout(soTimeout);
        options.setCoPerHost(coPerHost);
        options.setCoMultiplier(coMultiplier);

        // 集群模式
        if (StringUtil.isNotEmpty(seeds)) {

            if (StringUtil.isEmpty(user) || StringUtil.isEmpty(pwd)) {
                // 无鉴权信息
                return new MongoClient(seeds, db, options);
            } else {
                return new MongoClient(seeds, db, user, pwd, options);
            }

        } else if (StringUtil.isNotEmpty(host) && port != null) {

            // 单机模式
            if (StringUtil.isEmpty(user) || StringUtil.isEmpty(pwd)) {
                // 无鉴权信息
                return new MongoClient(host, port, db, options);
            } else {
                return new MongoClient(host, port, db, user, pwd, options);
            }
        }

        return null;
    }

}
